package utils

import (
	"chat/common"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"net/http"
	"time"
)

type Claims struct {
	User interface{} `json:"user"`
	jwt.RegisteredClaims
}

// GenerateToken JWT token生成函数
func (auth *Claims) GenerateToken(user interface{}) (string, error) {
	claims := &Claims{
		User: user,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "yitiaoyu",
			Subject:   "chat_room",
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// 使用指定的密钥签名token
	signedToken, err := token.SignedString([]byte(common.SECRET))
	if err != nil {
		return "", err
	}

	return signedToken, nil
}
func (auth *Claims) Middleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		tokenString := context.GetHeader("Authorization")
		if tokenString == "" {
			Result(http.StatusUnauthorized, "没有权限", context)
			context.Abort()
			return
		}
		claims, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
			// 验证token签名的密钥
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
			}
			return []byte(common.SECRET), nil
		})
		fmt.Println(err)
		if err != nil {
			Result(http.StatusUnauthorized, "token解析失败", context)
			context.Abort()
			return
		}

		if claims, ok := claims.Claims.(*Claims); ok {
			context.Set("user", claims.User)
		} else {
			Result(http.StatusUnauthorized, "无效的token", context)
			context.Abort()
			return
		}
	}
}
